package Utility;

public class ChatEncryption implements Encryption {

	@Override
	public String encrypt(String s) {
		return ROT46.encrypt(s);
	}

	@Override
	public String decrypt(String s) {
		return ROT46.encrypt(s);
	}
	
	 /**
	  * The ROT46 cipher.
	  * @author Leenix
	  *
	  */
	 static class ROT46 {
		final static int encryptionOffset = 46;
		 
		/**
		 * rot46(String) Use the rot46 encryption algorithm to encrypt/decrypt. As
		 * rot46 is a reciprocal cipher, any encrypted characters can be decrypted
		 * by passing them through again.
		 * 
		 * @param str String to be encrypted/decrypted
		 * @return Encrypted or decrypted string
		 */
		public static String encrypt(String str) {
			String encryptedString = "";

			// Perform encryption one character at a time.
			for (char c : str.toCharArray()) {
				encryptedString += encrypt(c);
			}
			return encryptedString;
		}

		/**
		 * rot46(char) Use the rot46 encryption algorithm to encrypt/decrypt a
		 * single character. As rot46 is a reciprocal cipher, any encrypted
		 * characters can be decrypted by passing them through again.
		 * 
		 * @param c
		 *            Character to be encrypted/decrypted
		 * @return Encrypted or decrypted character
		 */
		public static char encrypt(char c) {
			if (c >= '!' && c <= 'P') {
				c += encryptionOffset;
			} else if (c >= 'Q' && c <= '~') {
				c -= encryptionOffset;
			}
			return c;
		}
	}

}
